﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Collections;
using NewBee.Core.BusinessService;
using WebMvc_Survey.ApiAttributes;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace WebMvc_Survey.ApiControllers
{
    /// <summary>
    /// 用户登录
    /// </summary>
    [Route("api/[controller]")]
    public class LoginController : Controller
    {
        AgentFactory _AgentFactory = new AgentFactory();

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpBase]
        [HttpPost]
        public NewBee.Core.Data.Model.SuccessResult Post([FromForm]string username, [FromForm]string password)
        {
            NewBee.Core.Data.Model.SuccessResult _SuccessResult = new NewBee.Core.Data.Model.SuccessResult();
            if (string.IsNullOrEmpty(username))
            {
                _SuccessResult.Message = "请输入用户名";
                return _SuccessResult;
            }
            if (string.IsNullOrEmpty(password))
            {
                _SuccessResult.Message = "请输入密码";
                return _SuccessResult;
            }
            try
            {
                if (username.ToLower() == "zhulige"|| username.ToLower() == "open")
                {
                    if (password == "123456")
                    {
                        if (username.ToLower() == "zhulige")
                        {
                            Response.Cookies.Append("UserId", "Zhulige");
                            Response.Cookies.Append("UserName", "朱利戈");
                        }
                        else
                        {
                            Response.Cookies.Append("UserId", "Open");
                            Response.Cookies.Append("UserName", "Open");
                        }
                        _SuccessResult.Success = true;
                        _SuccessResult.Data = "teacher";
                    }
                    else {
                        _SuccessResult.Message = "密码错误";
                        return _SuccessResult;
                    }

                }
                else
                {
                    HttpClient _HttpClient = new HttpClient();
                    var response = _HttpClient.GetAsync("http://mmapi.open.com.cn/api/Account/getlogin?loginname=" + username + "&password=" + password + "&token=" + GetToken());
                    _SuccessResult = _SuccessResult.GetSuccessResult(response.Result.Content.ReadAsStringAsync().Result);
                    //_SuccessResult.Success = true;
                    //OES联调
                    if (_SuccessResult.Success)
                    {
                        Hashtable _Hashtable = (Hashtable)Newtonsoft.Json.JsonConvert.DeserializeObject(_SuccessResult.Data.ToString(), new Hashtable().GetType());
                        Response.Cookies.Append("UserId", System.Convert.ToString(_Hashtable["LoginName"]));
                        Response.Cookies.Append("UserName", System.Convert.ToString(_Hashtable["RealName"]));
                        Response.Cookies.Append("MobilePhone", System.Convert.ToString(_Hashtable["MobilePhone"]));
                        _SuccessResult.Data = "student";
                        if (System.Convert.ToString(_Hashtable["UserType"]) == "teacher")
                        {
                            NewBee.Core.Models.Survey_Share _Survey_Share = _AgentFactory.Survey_Share.GetByUserId(username);
                            if (_Survey_Share == null)
                            {
                                _Survey_Share = new NewBee.Core.Models.Survey_Share();
                                _Survey_Share.UserID = System.Convert.ToString(_Hashtable["LoginName"]);
                                _Survey_Share.UserName = System.Convert.ToString(_Hashtable["RealName"]);
                                _AgentFactory.Survey_Share.Insert(_Survey_Share);
                            }

                            _SuccessResult.Data = "teacher";
                        }
                    }
                }
            }
            catch (BusinessException ex)
            {
                _SuccessResult.Message = ex.Message;
            }
            catch (Exception ex)
            {
                _SuccessResult.Message = ex.Message;
            }
            return _SuccessResult;
        }

        ///// <summary>
        ///// 用户登录
        ///// </summary>
        ///// <param name="username"></param>
        ///// <param name="password"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public NewBee.Core.Data.Model.SuccessResult Post([FromQuery]string username, [FromQuery]string password)
        //{
        //    NewBee.Core.Data.Model.SuccessResult _SuccessResult = new NewBee.Core.Data.Model.SuccessResult();
        //    try
        //    {
        //        HttpClient _HttpClient = new HttpClient();
        //        var response = _HttpClient.GetAsync("http://mmapi.open.com.cn/api/Account/getlogin?loginname=" + username + "&password=" + password+"&token="+GetToken());
        //        _SuccessResult.Message = response.Result.Content.ReadAsStringAsync().Result;
        //    }
        //    catch (Exception ex)
        //    { }
        //    return _SuccessResult;
        //}

        /// <summary>
        /// GetToken
        /// </summary>
        private string GetToken()
        {
            NewBee.Core.Data.Model.SuccessResult _SuccessResult = new NewBee.Core.Data.Model.SuccessResult();
            try
            {
                HttpClient _HttpClient = new HttpClient();
                string client_id = "fae64940f1b354c1";
                string client_secret = "74a7e444685f44a8ba224a9f3e9f6310";

                string apiUrl = string.Format("http://mmapi.open.com.cn/api/Account/GetToken?client_id={0}&client_secret={1}"
                  , client_id, client_secret);
                var response = _HttpClient.GetAsync(apiUrl);

                _SuccessResult = _SuccessResult.GetSuccessResult(response.Result.Content.ReadAsStringAsync().Result);

                Hashtable _Hashtable = (Hashtable)Newtonsoft.Json.JsonConvert.DeserializeObject(_SuccessResult.Data.ToString(), new Hashtable().GetType());

                if (System.Convert.ToInt32(_Hashtable["expires_in"]) < 300)//判断如果过期时间时间小于300秒，则刷新token
                {
                    apiUrl = string.Format("http://mmapi.open.com.cn/api/Account/GetToken?client_id={0}&client_secret={1}&grant_type={2}&refresh_token={3}"
                        , client_id, client_secret, "refresh_token", _Hashtable["refresh_token"].ToString());

                    response = _HttpClient.GetAsync(apiUrl);

                    _SuccessResult = _SuccessResult.GetSuccessResult(response.Result.Content.ReadAsStringAsync().Result);

                    _Hashtable = (Hashtable)Newtonsoft.Json.JsonConvert.DeserializeObject(_SuccessResult.Data.ToString(), new Hashtable().GetType());
                }

                return _Hashtable["access_token"].ToString();
            }
            catch (Exception ex)
            { }
            return string.Empty;
        }

    }
}
